<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header" style="border-bottom: 1px solid #e4e7ed;padding-bottom: 10px;">
          <div class="title-container">
            <el-icon size="24">
              <Sell />
            </el-icon>
            <h2>入库管理</h2>
          </div>
          <div class="button-container">
            <el-button type="primary" @click="drawer2 = true"><el-icon>
                <el-icon>
                  <Plus />
                </el-icon>
              </el-icon>手动入库</el-button>
          </div>
        </div>
        <!-- 搜索 -->
        <el-card style="margin-top: 15px;border-radius: 10px;">
          <div class="search-container">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">

              <el-form-item label="入库单号">
                <el-input v-model="searchForm.Warehousing" placeholder="入库单号" class="search-input"
                  style="width: 250px;" />
              </el-form-item>
              <el-form-item label="采购单号">
                <el-input v-model="searchForm.procurement" placeholder="采购单号" class="search-input"
                  style="width: 250px;" />
              </el-form-item>
              <el-form-item label="供应商">
                <el-select v-model="searchForm.suppliers" placeholder="供应商" class="search-select" style="width: 250px;">
                  <el-option :label="item.supplier_name" :value="item.supplier_id" v-for="item in supplierList"
                    style="padding: 5px 10px;" />
                </el-select>
              </el-form-item>
              <el-date-picker v-model="searchForm.WarehousingDate" type="datetime" placeholder="入库时间"
                format="YYYY/MM/DD HH:mm:ss" style="width: 200px; margin-right: 30px" />
              <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="delhandleSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>

      </template>

      <el-table :data="tableData" style="width: 100%">

        <el-table-column label="序号" width="60">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span>{{ scope.row.in_id }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="入库单号" width="175">
          <template #default="scope">
            <div>
              <span>{{ scope.row.code }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="采购订单号" width="200">
          <template #default="scope">
            <div>
              <span>{{ scope.row.order?.code || '-' }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="供应商" width="125">
          <template #default="scope">
            <div>
              <span>{{ scope.row.supplier?.supplier_name || '-' }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="入库日期" width="200">
          <template #default="scope">
            <div>
              <span>{{ scope.row.in_date ? new Date(scope.row.in_date).toLocaleString() : '-' }}</span>

            </div>
          </template>
        </el-table-column>

        <el-table-column label="总金额" width="100">
          <template #default="scope">
            <div>
              <span>{{ scope.row.in_amount }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div v-if="scope.row.status == 0">状态: {{ getStatusText(0) }}</div>
                <div v-else-if="scope.row.status == 1">状态: {{ getStatusText(1) }}</div>
                <div v-else-if="scope.row.status == 2">状态: {{ getStatusText(2) }}</div>
                <div v-else>状态: {{ getStatusText(3) }}</div>
              </template>
              <template #reference>
                <el-tag :type="getStatusType(0)" v-if="scope.row.status == 0" style="padding: 5px 10px;">
                  {{ getStatusText(0) }}
                </el-tag>
                <el-tag :type="getStatusType(1)" v-else-if="scope.row.status == 1" style="padding: 5px 10px;">
                  {{ getStatusText(1) }}
                </el-tag>
                <el-tag :type="getStatusType(2)" v-else-if="scope.row.status == 2" style="padding: 5px 10px;">
                  {{ getStatusText(2) }}
                </el-tag>

                <el-tag :type="getStatusType(3)" v-else style="padding: 5px 10px;">
                  {{ getStatusText(3) }}
                </el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>

        <!-- 把最近入库日期格式化为yyyy-MM-dd HH:mm:ss -->
        <el-table-column label="操作人" width="200">
          <template #default="scope">
            <div>
              <span>{{ scope.row.updated_at ? new Date(scope.row.updated_at).toLocaleString() : '-' }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.$index, scope.row)">
              <el-icon style="margin-right: 5px;">
                <View />
              </el-icon>查看
            </el-button>
            <el-button size="small" @click="WarehouseReceipt(scope.$index, scope.row)">
              <el-icon style="margin-right: 5px;">
                <el-icon>
                  <PictureFilled />
                </el-icon>
              </el-icon>上传入库单据
            </el-button>
            <el-button size="small" @click="handleViewDetail(scope.$index, scope.row)" v-if="scope.row.status != 2"
              v-print="printObj">
              <el-icon style="margin-right: 5px;">
                <el-icon>
                  <Reading />
                </el-icon>
              </el-icon>打印
            </el-button>
            <el-button size="small" @click="UpdateDrawer(scope.$index, scope.row)" v-if="scope.row.status == 2">
              <el-icon style="margin-right: 5px;">
                <el-icon>
                  <Edit />
                </el-icon>
              </el-icon>编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 15, 20, 30]"
          :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
          :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

    </el-card>
    <!-- 入库明细抽屉组件 -->
    <el-drawer v-model="drawer" :direction="direction" size="70%" id="printMe">
      <template #header>
        <div class="no-print">
          <h4>入库明细</h4>
        </div>
      </template>
      <template #default>
        <div class="drawer-content">
          <!-- 打印标题 -->
          <div class="print-title">入库明细单</div>

          <!-- 打印时间 -->
          <div class="print-time">
            打印时间：{{ new Date().toLocaleString('zh-CN') }}
          </div>

          <div class="drawer-content-title">
            <h4>入库明细信息</h4>
          </div>
          <div class="drawer-content-form">
            <el-form :model="updateForm" :rules="rules" ref="formRef" label-width="80px"
              style="display: flex; justify-content: space-between;">
              <ul class="form-list">
                <li>
                  <p>入库日期</p>
                  <el-date-picker v-model="lookForm.in_date" type="date" value-format="yyyy-MM-dd" placeholder="选择入库日期"
                    style="width: 100%;" />
                </li>
                <li>
                  <p>入库类型</p>
                  <el-input v-if="lookForm.in_type == '1'" value="采购入库" />
                  <el-input v-else-if="lookForm.in_type == '2'" value="临时采购/赠品入库" />
                  <el-input v-else-if="lookForm.in_type == '3'" value="退货入库" />
                  <el-input v-else-if="lookForm.in_type == '4'" value="调拨入库" />
                  <el-input v-else-if="lookForm.in_type == '5'" value="盘盈入库" />

                </li>
                <li>
                  <p>采购订单号</p>
                  <el-input v-model="lookForm.po_code" />
                </li>
                <li>
                  <p>供应商</p>

                  <el-select v-model="searchForm.suppliers" placeholder="供应商" class="search-select"
                    style="width: 250px;">
                    <el-option :label="item.supplier_name" :value="item.supplier_id" v-for="item in supplierList"
                      style="padding: 5px 10px;" />
                  </el-select>

                </li>


                <li style="display: block;">
                  <p>备注</p>
                  <el-input v-model="lookForm.notes" type="textarea" :rows="4" style="width:100%" />
                </li>

              </ul>
            </el-form>


            <el-table :data="tableData2" style="width: 100%">
              <el-table-column label="#" width="30">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.goods_id }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="食材名称" width="100">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.name }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="规格型号" width="130">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.specification }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="单位" width="60">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.unit }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="入库单价" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.in_price }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="采购总数" width="100">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goodsOrderItems && scope.row.goodsOrderItems[scope.$index] ?
                      scope.row.goodsOrderItems[scope.$index].ordered_count : '-' }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="实到总数" width="100">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.in_count }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="全部入库" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.goods_id }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="总价" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.inventoryIn.in_amount }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="生产日期" width="130">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <!-- 格式化生产日期 -->
                    <span>{{ scope.row.production_date ? new Date(scope.row.production_date).toLocaleString('zh-CN', {
                      year: 'numeric', month: '2-digit', day: '2-digit'
                    }) : '-' }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="保质期" width="130">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <!-- 格式化过期日期 -->
                    <span>{{ scope.row.expiration_date ? new Date(scope.row.expiration_date).toLocaleString('zh-CN', {
                      year: 'numeric', month: '2-digit', day: '2-digit'
                    }) : '-' }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="仓库" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.house.name }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="存储区域" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.area.area_name }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="立即出库" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.goods_id }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="立即出库" width="180">
                <template #default="scope">
                  <el-popover effect="light" trigger="hover" placement="top" width="auto">
                    <template #default>
                      <div>状态: {{ scope.row.is_out ? '已立即出库' : '未立即出库' }}</div>
                    </template>
                    <template #reference>
                      <el-tag>{{ scope.row.is_out ? '是' : '否' }}</el-tag>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>

            </el-table>


          </div>
          <!-- 总价 -->
          <div class="drawer-content-zongjia">
            <p>总金额</p>
            <p>{{ totalAmount }}</p>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <!-- <el-button @click="cancelClick"> 取消</el-button> -->
          <el-button type="primary" @click="handleSubmit"> 关闭</el-button>
        </div>
      </template>
    </el-drawer>



    <!-- 手动入库抽屉组件 -->
    <el-drawer v-model="drawer2" :direction="direction" size="70%">
      <template #header>
        <h4>手动入库</h4>
      </template>
      <template #default>
        <div class="drawer-content">
          <div class="drawer-content-title">
            <h4>入库信息</h4>
          </div>
          <div class="drawer-content-form">
            <el-form :model="addform" :rules="rules" ref="formRef" label-width="80px"
              style="display: flex; justify-content: space-between;">
              <ul class="form-list">

                <li>
                  <p>入库类型</p>
                  <el-select v-model="addform.in_type" placeholder="入库类型" class="search-select" style="width:100%;">
                    <el-option label="采购入库" value="1" style="padding: 5px 10px;" />
                    <el-option label="临时采购/赠品入库" value="2" style="padding: 5px 10px;" />
                    <el-option label="退货入库" value="3" style="padding: 5px 10px;" />
                    <el-option label="调拨入库" value="4" style="padding: 5px 10px;" />
                    <el-option label="盘盈入库" value="5" style="padding: 5px 10px;" />
                  </el-select>
                </li>
                <li>
                  <p>采购订单号</p>
                  <el-input v-model="addform.po_code" @change="FoodChange" />
                </li>



                <li style="display: block;">
                  <p>备注</p>
                  <el-input v-model="addform.notes" type="textarea" :rows="4" style="width:100%" />
                </li>

              </ul>
            </el-form>


            <div class="drawer-content-title">
              <h4>盘点明细</h4>
              <!-- <el-button type="primary" @click="addInventoryRow"><el-icon>
                  <Plus />
                </el-icon>添加行</el-button> -->
            </div>
            <!-- 盘点明细表格 -->
            <div class="inventory-detail-table">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>食材名称</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>入库单价</th>
                    <th>采购总数</th>
                    <th>实到总数</th>
                    <th>全部入库</th>
                    <th>总价</th>
                    <th>生产日期</th>
                    <th>保质期</th>
                    <th>仓库</th>
                    <th>存储区域</th>
                    <th>立即出库</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in inventoryDetails" :key="index">
                    <td>{{ index + 1 }}</td>

                    <!-- <td>
                      <el-select v-model="item.foodName" placeholder="请选择食材" >
                        <el-option v-for="item in goodsList" :key="item.id" :label="item.name" :value="item.goods_id"
                          style="padding-left: 10px;" />
                      </el-select>
                    </td> -->
                    <!-- 食材名称 -->
                    <td>{{ item.goodsInfo?.name }}</td>
                    <!-- 规格型号 -->
                    <td>{{ item.goodsInfo?.specification }}</td>
                    <!-- 单位 -->
                    <td>{{ item.goodsInfo?.unit }}</td>
                    <!-- 入库单价 -->
                    <td>
                      <!-- {{ item.in_price }} -->
                      <el-input-number v-model="item.unit_price" :min="0" @change="calculateDiff" />
                    </td>
                    <!-- 采购总数 -->
                    <td>
                      <el-input-number v-model="item.ordered_count" :min="0" @change="calculateDiff" />
                      <!-- {{ item.ordered_count }} -->
                    </td>
                    <!-- 实到总数 -->
                    <td><el-input-number v-model="item.in_count" :min="0" @change="calculateDiff" /></td>
                    <!-- 全部入库 -->
                    <td>
                      <el-checkbox v-model="item.allInWarehouse" @change="handleAllInWarehouseChange(index, $event)">
                        全部入库
                      </el-checkbox>
                    </td>
                    <!-- 总价 -->
                    <td>{{ item.subtotal }}</td>
                    <!-- 生产日期 -->
                    <td><el-date-picker v-model="item.production_date" type="date" value-format="YYYY-MM-DD"
                        placeholder="选择生产日期" style="width:150px;" /></td>
                    <!-- 保质期 -->
                    <td><el-date-picker v-model="item.expiration_date" type="date" value-format="YYYY-MM-DD"
                        placeholder="选择保质期" style="width:150px;" /></td>
                    <!-- 仓库 -->
                    <td><el-select v-model="item.house" placeholder="选择仓库" class="search-select" style="width:100px;"
                        @change="handleHouseChange(index, $event)">
                        <el-option v-for="(warehouse, index) in warehouseList" :key="index" :label="warehouse.name"
                          :value="warehouse.house_id" style="padding: 5px 10px;" />
                      </el-select></td>
                    <!-- 存储区域 -->
                    <td><el-select v-model="item.house_area" placeholder="选择仓库区域" class="search-select"
                        style="width:100px;">
                        <el-option v-for="(area, index) in item.houseAreas" :key="index" :label="area.area_name"
                          :value="area.area_id" style="padding: 5px 10px;" />
                      </el-select></td>
                    <!-- 立即出库 -->
                    <td>
                      <el-checkbox v-model="item.immediateOutbound"
                        @change="handleImmediateOutboundChange(index, $event)">
                        立即出库
                      </el-checkbox>
                    </td>
                    <!-- <td>
                      <el-input-number v-model="item.actualStock" :min="0" @change="calculateDiff" />
                    </td> -->
                    <!-- <td :class="{ negative: item.diff !== null && item.diff < 0 }">{{ item.diff }}</td> -->
                    <!-- <td>{{ item.systemStock }}</td> -->
                    <td>
                      <el-button type="danger" :icon="Delete" size="small"
                        @click="deleteInventoryRow(index)"></el-button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="drawer-content-zongjia">
              <p>总金额</p>
              <p>{{ totalAmount }}</p>
            </div>

            <div class="drawer-content-title" style="margin-top: 20px;">
              <h4>入库信息</h4>
            </div>
            <div>
              <el-form :model="addform" :rules="rules" ref="formRef2" label-width="80px"
                style="display: flex; justify-content: space-between;">
                <ul class="form-list">
                  <li>
                    <p>交货人姓名</p>
                    <el-input v-model="addform.deliverer_name" />
                  </li>
                  <li>
                    <p>交货人电话</p>
                    <el-input v-model="addform.deliverer_phone" />
                  </li>
                  <li>
                    <p>仓库主管</p>
                    <el-select v-model="addform.house_uid" placeholder="选择仓库主管" class="search-select"
                      style="width:100%;">
                      <el-option v-for="item in kuguanList" :key="item.user_id || item.id" :label="item.user_name"
                        :value="item.user_id || item.id" style="padding: 5px 10px;" />
                    </el-select>
                  </li>
                  <li>
                    <p>财务主管</p>
                    <el-select v-model="addform.finance_uid" placeholder="请选择财务主管" class="search-select"
                      style="width:100%;">
                      <el-option v-for="item in caigouList" :key="item.user_id || item.id" :label="item.user_name"
                        :value="item.user_id || item.id" style="padding: 5px 10px;" />

                    </el-select>
                  </li>
                  <li>
                    <p>经办人</p>
                    <el-input v-model="userName" readonly />
                  </li>
                </ul>
              </el-form>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick"> 取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 提交</el-button>
        </div>
      </template>
    </el-drawer>



    <!-- 编辑入库 -->
    <el-drawer v-model="drawer3" :direction="direction" size="70%">
      <template #header>
        <h4>编辑入库</h4>
      </template>
      <template #default>
        <div class="drawer-content">
          <div class="drawer-content-title">
            <h4>入库明细信息</h4>
          </div>
          <div class="drawer-content-form">
            <el-form :model="updateForm" :rules="rules" ref="formRef" label-width="80px"
              style="display: flex; justify-content: space-between;">
              <ul class="form-list">
                <li>
                  <p>入库日期</p>
                  <el-date-picker v-model="update.in_date" type="date" value-format="yyyy-MM-dd" placeholder="选择入库日期"
                    style="width: 100%;" />
                </li>
                <li>
                  <p>入库类型</p>
                  <el-input v-if="update.in_type == '1'" value="采购入库" />
                  <el-input v-else-if="update.in_type == '2'" value="临时采购/赠品入库" />
                  <el-input v-else-if="update.in_type == '3'" value="退货入库" />
                  <el-input v-else-if="update.in_type == '4'" value="调拨入库" />
                  <el-input v-else-if="update.in_type == '5'" value="盘盈入库" />

                </li>
                <li>
                  <p>采购订单号</p>
                  <el-input v-model="update.po_code" />
                </li>
                <li></li>
                <li style="display: block;">
                  <p>备注</p>
                  <el-input v-model="update.notes" type="textarea" :rows="4" style="width:100%" />
                </li>

              </ul>
            </el-form>


            <el-table :data="tableData2" style="width: 100%">
              <el-table-column label="#" width="30">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.goods_id }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="食材名称" width="100">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.name }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="规格型号" width="130">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.specification }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="单位" width="60">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.unit }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="入库单价" width="80">
                <template #default="scope">
                  <!-- <div style="display: flex; align-items: center">
                    <span>{{ scope.row.in_price }}</span>
                  </div> -->
                  <el-input v-model="scope.row.in_price" />
                </template>

              </el-table-column>
              <el-table-column label="采购总数" width="100">
                <template #default="scope">
                  <!-- <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goodsOrderItems && scope.row.goodsOrderItems[scope.$index] ?
                      scope.row.goodsOrderItems[scope.$index].ordered_count : '-' }}</span>
                  </div> -->
                  <el-input v-model="scope.row.in_count" />
                </template>

              </el-table-column>
              <el-table-column label="实到总数" width="100">
                <template #default="scope">
                  <!-- <div style="display: flex; align-items: center">
                    <span>{{ scope.row.in_count }}</span>
                  </div> -->
                  <el-input v-model="scope.row.in_count" />
                </template>

              </el-table-column>
              <el-table-column label="全部入库" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.goods.goods_id }}</span>
                  </div>

                </template>

              </el-table-column>
              <el-table-column label="总价" width="80">
                <template #default="scope">
                  <!-- <div style="display: flex; align-items: center">
                    <span>{{ scope.row.inventoryIn.in_amount }}</span>
                  </div> -->
                  <el-input v-model="scope.row.inventoryIn.in_amount" />
                </template>

              </el-table-column>
              <el-table-column label="生产日期" width="130">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <!-- 格式化生产日期 -->
                    <span>{{ scope.row.production_date ? new Date(scope.row.production_date).toLocaleString('zh-CN', {
                      year: 'numeric', month: '2-digit', day: '2-digit'
                    }) : '-' }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="保质期" width="130">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <!-- 格式化过期日期 -->
                    <span>{{ scope.row.expiration_date ? new Date(scope.row.expiration_date).toLocaleString('zh-CN', {
                      year: 'numeric', month: '2-digit', day: '2-digit'
                    }) : '-' }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="仓库" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.house.name }}</span>
                  </div>
                </template>

              </el-table-column>
              <el-table-column label="存储区域" width="80">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span>{{ scope.row.area.area_name }}</span>
                  </div>
                </template>

              </el-table-column>

              <el-table-column label="立即出库" width="180">
                <template #default="scope">
                  <el-popover effect="light" trigger="hover" placement="top" width="auto">
                    <template #default>
                      <div>状态: {{ scope.row.is_out ? '已立即出库' : '未立即出库' }}</div>
                    </template>
                    <template #reference>
                      <el-tag>{{ scope.row.is_out ? '是' : '否' }}</el-tag>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>

            </el-table>


          </div>
          <!-- 总价 -->
          <div class="drawer-content-zongjia">
            <p>总金额</p>
            <p>{{ totalAmount }}</p>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <!-- <el-button @click="cancelClick"> 取消</el-button> -->
          <el-button type="primary" @click="handleSubmit"> 关闭</el-button>
        </div>
      </template>
    </el-drawer>



    <!-- 上传入库单据 -->
    <el-drawer v-model="drawer4" :direction="direction" size="30%">
      <template #header>
        <h4>上传入库单据</h4>
      </template>
      <template #default>
        <div class="drawer-content">
          <div class="drawer-content-title">
            <p>请上传入库单据</p>
          </div>
        </div>

        <div>
          <p>请上传入库单据图片</p>
          <el-upload class="avatar-uploader" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>


      </template>
      <template #footer>
        <div style="flex: auto">
          <!-- <el-button @click="cancelClick"> 取消</el-button> -->
          <el-button type="primary" @click="handleSubmit"> 关闭</el-button>
        </div>
      </template>
    </el-drawer>


  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { Timer, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage, dayjs } from 'element-plus'
import inventoryinApi from '../../api/inventoryin'
import { useInventoryinStore } from '../../stores/inventoryin'
import inventoryApi from '../../api/inventory'

import { Plus } from '@element-plus/icons-vue'

// 入库列表数据
const tableData = ref([])
// 入库明细表格数据
const tableData2 = ref([])
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const size = ref('default')
const background = ref(false)
const disabled = ref(false)

// 计算总金额 - 支持入库详情(tableData2)和库存详情(inventoryDetails)
const totalAmount = computed(() => {
  // 优先使用tableData2（入库详情），如果为空则使用inventoryDetails（库存详情）
  const dataSource = Array.isArray(tableData2.value) && tableData2.value.length > 0
      ? tableData2.value
      : (Array.isArray(inventoryDetails?.value) ? inventoryDetails.value : [])

  if (!Array.isArray(dataSource) || dataSource.length === 0) {
    return '0.00'
  }

  const sum = dataSource.reduce((total, row) => {
    // 首先检查是否已有计算好的subtotal字段
    if (row?.subtotal !== undefined) {
      const subtotal = parseFloat(row.subtotal)
      return total + (isNaN(subtotal) ? 0 : subtotal)
    }
    
    // 手动入库时使用unit_price和in_count计算
    if (row?.unit_price !== undefined && row?.in_count !== undefined) {
      const count = parseFloat(row.in_count || 0)
      const price = parseFloat(row.unit_price || 0)
      const itemTotal = count * price
      return total + (isNaN(itemTotal) ? 0 : itemTotal)
    }
    
    // 原有逻辑作为备选
    const count = parseFloat(row?.in_count || row?.ordered_count || 0)
    const price = parseFloat(row?.goodsInfo?.in_price || row?.in_price || 0)
    const itemTotal = count * price
    // 检查是否为有效数字
    return total + (isNaN(itemTotal) ? 0 : itemTotal)
  }, 0)

  // 格式化为保留2位小数的字符串
  return sum.toFixed(2)
})

const lookForm = ref({
  notes: '',
  in_date: null,
  in_type: null,
  po_code: null,
  supplier: null
})

// 添加缺失的变量定义
const drawer = ref(false)
const drawer2 = ref(false)
const drawer3 = ref(false)
const drawer4 = ref(false)
const direction = ref('rtl') // 或其他合适的默认值
const updateForm = ref({
  goods_name: '',
  warehouse: '',
  area_id: '',
  Specifications: '',
  unit: '',
  inventory: '',
  adjustment: 0,
  adjustmentType: '',
  reason: '',
  related_order: '',
  notes: ''
})
const rules = ref({})
const formRef = ref(null)
const goodsList = ref([])
const warehouseList = ref([])
const areaList = ref([])
const inventoryDetailForm = ref({})


let searchForm = ref({
  Warehousing: null,
  procurement: null,
  suppliers: null,
  WarehousingDate: null // 从模板中看到的日期选择器绑定
})

let addform = ref({
  in_type: null,
  po_code: null,
  supplier: null,
  notes: '',
  deliverer_name: null,
  house_uid: null,
  finance_uid: null,
  user_uid: null,
  in_amount: null,
  deliverer_phone: null,
})

const inventoryDetails = ref([
  {
    goods_name: '',
    warehouse: '',
    area_id: '',
    Specifications: '',
    unit: '',
    inventory: '',
    adjustment: 0,
    adjustmentType: '',
    reason: '',
    related_order: '',
    notes: '',
    house: '',
    house_area: '',
    production_date: '',
    expiration_date: '',
    houseAreas: [],
    allInWarehouse: false,  // 全部入库状态
    immediateOutbound: false  // 立即出库状态
  }
])

const update = ref({
  goods_name: '',
  warehouse: '',
  area_id: '',
  Specifications: '',
  unit: '',
  inventory: '',
  adjustment: 0,
  adjustmentType: '',
  reason: '',
  related_order: '',
  notes: ''
})



const handleViewDetail = async (index, row) => {
  drawer.value = true
  console.log("查看第" + index + "条入库记录详情:", row)
  // 添加可选链操作符以防止属性访问错误
  lookForm.value.in_date = row.in_date
  lookForm.value.in_type = row.in_type
  lookForm.value.po_code = row.order?.code || '-'
  lookForm.value.supplier = row.supplier?.supplier_name || '-'
  lookForm.value.notes = row.notes || ''
  // 使用正确的API导入
  try {
    // 调用获取订单详情的函数
    await getGoodsOrderDetail(row.order.order_id)
  } catch (error) {
    console.error('获取入库明细出错:', error)
    ElMessage.error('获取入库存明细时发生错误')
  }
}

const kuguanList = ref([])
const caigouList = ref([])

// 获取用户列表
const getUserList = async () => {
  try {
    console.log('开始获取用户列表...')
    const kuguan = await inventoryinApi.getUserList({
      role_id: 2,
      page: 1,
      pageSize: 1000
    })
    console.log('仓库主管数据:', kuguan)
    kuguanList.value = kuguan.data || []

    const caigou = await inventoryinApi.getUserList({
      role_id: 3,
      page: 1,
      pageSize: 1000
    })
    console.log('财务主管数据:', caigou)
    caigouList.value = caigou.data || []

    console.log('kuguanList.value:', kuguanList.value)
    console.log('caigouList.value:', caigouList.value)
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error(error.message || '获取用户列表失败')
  }
}
getUserList()

// deep: true 用于深度监听数组或对象的变化

// 获取仓库列表
const SetHouseLise = async () => {
  try {
    const res = await inventoryApi.getWarehouse({
      page: 1,
      pageSize: 1000
    })
    console.log(res.data, "搜索框的仓库id")
    if (res.code === 0) {
      // 检查数据字段名称，可能是data或list
      warehouseList.value = res.data.list || []
      // 添加日志检查返回的数据结构
      console.log('仓库数据字段:', Object.keys(res.data.data?.[0] || res.data.list?.[0] || {}))
    } else {
      ElMessage.error(res.msg || '获取仓库列表失败')
      return null
    }
  } catch (error) {
    ElMessage.error(error.message || '获取仓库列表失败')
  }
}
SetHouseLise()

const houseArea = ref([])
// 处理仓库选择变化
const handleHouseChange = async (rowIndex, val) => {
  console.log(`第${rowIndex + 1}行仓库选择变化:`, val)

  // 获取当前行的数据
  const currentItem = inventoryDetails.value[rowIndex]
  if (!currentItem) {
    console.error('找不到当前行数据:', rowIndex)
    return
  }

  try {
    // 这里可以添加根据仓库ID获取区域的逻辑
    const res = await inventoryApi.getAreaInfo({
      page: 1,
      pageSize: 1000,
      house_id: val
    })
    console.log(res.data, "仓库区域列表")

    if (res.code === 0) {
      // 只更新当前行的仓库区域数据
      currentItem.houseAreas = res.data || []
      // 清空当前行已选择的区域，因为仓库变了
      currentItem.house_area = null

      console.log(`第${rowIndex + 1}行仓库区域数据已更新:`, currentItem.houseAreas)
    } else {
      ElMessage.error(res.msg || '获取仓库区域列表失败')
    }
  } catch (error) {
    console.error('获取仓库区域列表出错:', error)
    ElMessage.error('获取仓库区域列表时发生错误')
  }
}



// 根据id获取订单详情
const getGoodsOrderDetail = async (order_id) => {
  try {
    const res = await inventoryinApi.getGoodsOrderDetail({ order_id })
    if (res.code === 0 || res.code === 200) {
      tableData2.value = res.data || []

      console.log('订单详情:', tableData2.value)
    } else {
      ElMessage.error(res.msg || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情出错:', error)
    ElMessage.error('获取订单详情时发生错误')
  }
}


async function getGoodsList() {
  try {
    const res = await inventoryApi.getGoods({
      page: 1,
      pageSize: 1000
    })
    console.log(res.data, "搜索框的食材id")
    if (res.code === 0) {
      goodsList.value = res.data.data
      // inventoryStore.goodsList = res.data.list
    } else {
      ElMessage.error(res.msg || '获取商品列表失败')
      return null
    }
  } catch (error) {
    ElMessage.error(error.message || '获取商品列表失败')
  }
}
getGoodsList()


// 商品变化之后
const onFoodChange = async (val) => {
  console.log(val)
  const res = await inventoryApi.getGoods({
    goods_id: val
  })
  console.log(res)
}

// FoodChange函数已在文件末尾重新定义，处理采购单号查询和食材选择功能

const handleDelete = (index, row) => {
  console.log('删除操作 - 索引:', index, '数据:', row)
  // 这里可以添加删除确认和实际删除逻辑
}

// 添加缺失的函数定义
const handleGoodsChange = () => {
  console.log('商品改变:', updateForm.value.goods_name)
}

const getAreaList = () => {
  console.log('获取区域列表 - 仓库ID:', updateForm.value.warehouse)
  // 这里可以添加根据仓库获取区域的逻辑
}

const getStockList = () => {
  console.log('获取库存列表 - 区域ID:', updateForm.value.area_id)
  // 这里可以添加根据区域获取库存的逻辑
}

const cancelClick = () => {
  console.log('取消操作')
  drawer.value = false
}

const user_id = ref(null)

onMounted(async () => {
  // 读取本地存储的某个键的值，替换为实际的 key（如 'role_id'、'inventory' 等）
  user_id.value = localStorage.getItem('user_id');
  console.log('获取到的存储数据：', user_id.value); // 此处即可拿到对应的值"1"

  // 调用获取供应商列表的函数
  await supplier();
  await GetUserName(user_id);
});


const userName = ref('')
const GetUserName = async (user_id) => {
  try {
    const res = await inventoryinApi.GetUserName({
      user_id: user_id.value
    })

    // 添加安全检查，防止访问undefined的属性
    if (res.data && res.data.length > 0 && res.data[0]) {
      console.log(res.data[0].user_name)
      userName.value = res.data[0].user_name || ''
      if (res.code === 0 || res.code === 200) {
        inventoryinStore.userName = res.data || ''
      } else {
        ElMessage.error(res.msg || '获取用户姓名失败')
      }
    } else {
      console.warn('用户数据为空或格式不正确:', res.data)
      userName.value = ''
      ElMessage.warning('未找到用户信息')
    }
  } catch (error) {
    console.error('获取用户姓名出错:', error)
    ElMessage.error(error.message || '获取用户姓名失败')
  }
}



// 手动入库
// PO20251004021
const handleSubmit = async () => {
  try {
    console.log(form.value, "其他需要的数据")
    console.log('提交表单数据:', addform.value)
    
    // 检查inventoryDetails是否存在且为数组
    if (!Array.isArray(inventoryDetails.value)) {
      console.error('inventoryDetails不是有效的数组')
      ElMessage.error('数据格式错误')
      return
    }
    
    // 直接提交整个数组和总金额到后端，不再循环
    const result = await inventoryinStore.AddInventoryin({
      //订单id
      order_id: form.value?.data?.orderInfo?.order_id,
      // 入库类型
      in_type: addform.value.in_type || '1',
      // 接收人id
      receiver_uid: addform.value.receiver_uid || user_id.value,
      // 库管id
      house_uid: addform.value.house_uid,
      // 财务id
      finance_uid: addform.value.finance_uid,
      // 备注
      notes: addform.value.notes,
      // 配送员姓名
      deliverer_name: addform.value.deliverer_name,
      // 配送员手机号 
      deliverer_phone: addform.value.deliverer_phone,
      // 直接传递整个inventoryDetails数组
      inventoryDetails: inventoryDetails.value,
      // 传递总金额
      in_amount: totalAmount.value,
    })
    console.log(result)

    // 由于store中的AddInventoryin方法只返回res.data或null
    // 成功时返回非null值，失败时返回null
    if (result.success == true) {
      // 注意：store中已经显示了成功消息，这里不再重复显示
      drawer2.value = false
      // 将getInventoryList放在try-catch中单独处理，避免其错误影响主流程
      try {
        getInventoryList() // 重新获取列表数据
      } catch (getListError) {
        console.error('获取列表数据时发生错误:', getListError)
        // 这里可以选择是否显示错误消息，因为主要操作已经成功
      }
    } else {
      // 失败消息在store中已经显示，这里可以不重复显示
      console.log('提交失败，store中已显示错误消息')
    }
  } catch (error) {
    // 启用错误日志以便调试
    console.error('提交时发生错误:', error)
    // 当数据库已经写入数据但仍报错时，给用户一个友好提示
    // 这里可以提供重试或确认操作的选项
    ElMessage.warning('操作已提交，请确认数据是否已正确保存。如有疑问，请刷新页面查看最新数据。')
  }
}

const UpdateDrawer = async (index, row) => {
  drawer3.value = true
  console.log(row.order.order_id)
  update.value.in_date = row.in_date
  update.value.in_type = row.in_type
  update.value.po_code = row.order?.code || '-'
  update.value.supplier = row.supplier?.supplier_name || '-'
  update.value.notes = row.notes || ''
  getGoodsOrderDetail(row.order.order_id)
}



// 总条数
const total = ref(0)

const inventoryinStore = useInventoryinStore()


async function getInventoryList() {
  try {
    console.log('开始获取入库列表')
    const params = {
      page: currentPage4.value,
      pageSize: pageSize4.value,
      code: searchForm.value.Warehousing,
      order_code: searchForm.value.procurement,
      supplier_id: searchForm.value.suppliers
    }

    // 只有当WarehousingDate存在时才添加in_date参数
    if (searchForm.value.WarehousingDate) {
      params.in_date = dayjs(searchForm.value.WarehousingDate).format('YYYY-MM-DD')
    }

    const res = await inventoryinApi.getInventoryinList(params)
    // console.log('入库列表API响应:', res)
    console.log('响应数据:', res.data)

    if (res.code === 0 || res.code === 200) { // 同时支持0和200状态码
      console.log('API返回数据结构:', res)

      // 确保tableData始终是数组，防止'data is not iterable'错误
      if (res.data && Array.isArray(res.data.data)) {
        tableData.value = res.data.data
      } else if (res.data && Array.isArray(res.data)) {
        tableData.value = res.data
      } else if (Array.isArray(res)) {
        tableData.value = res
      } else {
        // 如果都不是数组，设置为空数组
        tableData.value = []
        console.warn('返回的数据不是数组格式，已设置为空数组')
      }

      // 安全地获取总数
      total.value = res.total || res.data?.total || tableData.value.length

      console.log('表格数据已设置(类型):', Array.isArray(tableData.value) ? '数组' : typeof tableData.value)
      console.log('表格数据长度:', tableData.value.length)
      console.log('总数已设置:', total.value)
    } else {
      const errorMsg = res.msg || '获取库存列表失败'
      console.error('API调用失败:', errorMsg)
      ElMessage.error(errorMsg)
      // 出错时设置空数组，防止表格渲染错误
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取库存列表时发生错误:', error)
    ElMessage.error(error.message || '获取库存列表失败')
  }
}
getInventoryList()


// 每页条数
const handleSizeChange = (val) => {
  pageSize4.value = val
  getInventoryList()
  console.log(`${val} items per page`)
}
// 页码
const handleCurrentChange = (val) => {

  currentPage4.value = val
  getInventoryList()
  console.log(`current page: ${val}`)
}






const handleSearch = () => {
  // 搜索时重置页码为1
  currentPage4.value = 1
  // 添加搜索后获取数据的逻辑
  getInventoryList()
  console.log('执行搜索:', searchForm.value)
}

const delhandleSearch = () => {
  // 重置为与初始定义一致的结构
  searchForm.value = {
    Warehousing: null,
    procurement: null,
    suppliers: null,
    WarehousingDate: null
  }
  // 重置后也重置页码并重新获取数据
  currentPage4.value = 1
  getInventoryList()
  console.log('重置搜索条件')
}

// 打印配置对象
const printObj = ref({
  id: 'printMe', // 要打印的元素ID
  popTitle: '入库详情', // 打印标题
  extraCss: '', // 额外的CSS
  extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>' // 额外的head标签
})

// 获取供应商列表

const supplierList = ref([])
const supplier = async () => {
  console.log('开始获取供应商列表')
  try {
    // 直接调用API而不是store方法，因为store方法不返回结果
    const res = await inventoryinApi.getSupplierList({
      page: 1,
      pageSize: 1000
    })
    console.log('供应商API响应:', res)

    // 同时检查200和0状态码，以兼容不同的后端返回格式
    if (res.code === 200 || res.code === 0) {
      supplierList.value = res.data.data
      console.log('供应商列表已设置:', supplierList.value)
    } else {
      console.error('获取供应商列表失败:', res.msg || '未知错误')
    }
  } catch (error) {
    console.error('获取供应商列表时发生错误:', error)
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '已做废';
    case 1: return '待收货';
    case 2: return '收货中';
    case 3: return '已完成';
  }
};

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'danger';  // 已作废
    case 1: return 'warning';  // 待收货
    case 2: return 'info';  // 收货中
    case 3: return 'success';  // 已完成
  }
};


function addInventoryRow() {
  inventoryDetails.value.push({
    foodName: '',
    spec: '',
    unit: '',
    systemStock: 0,
    actualStock: null,
    diff: null,
    remark: '',
    allInWarehouse: false,  // 全部入库状态
    immediateOutbound: false,  // 立即出库状态
    houseAreas: [],  // 为新行添加独立的仓库区域数组
    production_date: '',  // 添加生产日期字段
    expiration_date: ''   // 添加保质期字段
  })
}

// 删除盘点行
function deleteInventoryRow(index) {
  inventoryDetails.value.splice(index, 1)
}

// 处理全部入库状态变化
const handleAllInWarehouseChange = (index, value) => {
  console.log(`第${index + 1}行全部入库状态:`, value)
  // 如果选择了全部入库，可以在这里添加相关逻辑
  if (value) {
    // 例如：自动设置实到总数等于采购总数
    const item = inventoryDetails.value[index]
    if (item.ordered_count && !item.in_count) {
      item.in_count = item.ordered_count
      calculateDiff()
    }
  }
}

// 处理立即出库状态变化
const handleImmediateOutboundChange = (index, value) => {
  console.log(`第${index + 1}行立即出库状态:`, value)
  // 如果选择了立即出库，可以在这里添加相关逻辑
  if (value) {
    // 例如：可以设置出库相关字段或显示出库表单
    const item = inventoryDetails.value[index]
    console.log(`准备立即出库: ${item.goodsInfo?.name || item.foodName}`)
  }
}

// 计算差异和小计函数
const calculateDiff = () => {
  inventoryDetails.value.forEach(item => {
    // 使用in_count计算实际差异
    item.diff = (parseFloat(item.in_count) || 0) - (parseFloat(item.systemStock) || 0)
    // 计算小计金额
    item.subtotal = (parseFloat(item.unit_price) || 0) * (parseFloat(item.in_count) || 0)
  })
}


const add_id = ref(null)
// 添加入库表单
const form = ref()
// 选择食材时自动填充规格、单位和系统库存 - 同时处理采购单号查询
async function FoodChange(val = null) {

  // 如果传入了值，则更新add_id（原功能）
  if (val !== null) {
    add_id.value = val
  }

  // 获取采购单号（从表单中）
  const poCode = addform.value.po_code

  try {
    // 调用API根据采购单号获取订单详情
    const res = await inventoryinApi.GetInventoryinDetail({
      code: poCode
    })
    console.log(res)
    form.value = res
    if (res.code == 0 && res.data && res.data.orderItems) {
      // 为每个项目添加in_count字段，默认值为ordered_count
      inventoryDetails.value = res.data.orderItems.map(item => ({
        ...item,
        in_count: item.ordered_count, // 设置实到总数默认等于采购总数
        allInWarehouse: false,  // 全部入库状态
        immediateOutbound: false,  // 立即出库状态
        houseAreas: [],  // 为每行添加独立的仓库区域数组
        production_date: '',  // 添加生产日期字段
        expiration_date: ''   // 添加保质期字段
      }))
    }
    console.log(inventoryDetails.value)

  } catch (error) {
    console.error('获取订单信息出错:', error)
    ElMessage.error('获取订单信息时发生错误，请检查网络或联系管理员')
  }
}

// 根据仓库ID获取对应的区域列表
const getWarehouseAreas = (houseId) => {
  if (!houseId) return []

  // 根据仓库ID从warehouseList中找到对应的仓库
  const warehouse = warehouseList.value.find(w => w.house_id === houseId)

  // 如果找到仓库且有区域数据，返回区域列表
  if (warehouse && warehouse.areas) {
    return warehouse.areas
  }

  // 如果没有区域数据，返回空数组或默认区域
  return []
}

// 处理入库单据上传
const WarehouseReceipt = (index, row) => {
  console.log(`第${index + 1}行准备上传入库单据:`, row)
  drawer4.value = true
  // 可以添加上传逻辑，例如调用API上传文件
}


const imageUrl = ref('')

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be png format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
  list-style: none;
}

.app-container {
  // background-color: #fff;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title-container {
      width: 120px;
      justify-content: space-evenly;
      display: flex;
      align-items: center;
    }

    .button-container {
      width: 240px;
      justify-content: space-between;
      display: flex;
      align-items: center;

    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.box-card {
  border-radius: 10px;
}

.demo-pagination-block,
.demo-pagination-block {
  margin-top: 20px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 减小抽屉组件header的高度 */
:deep(.el-drawer__header) {
  // padding: 10px 20px;
  // padding: -20 20px;
  margin-bottom: 0px;
  height: auto;
}

:deep(.el-drawer__header h4) {
  margin: 0;
  font-size: 16px;
  line-height: 1.5;
}


.drawer-content-title {
  border-bottom: 1px solid #ccc;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;

  h4 {
    color: #1b82f1;
  }
}

:deep(.el-form-item--label-right .el-form-item__label) {
  justify-content: flex-start;
  text-align: right;
}

:deep(.el-button) {
  padding: 8px 16px;
}

.form-list {
  margin: 20px 0;
  width: 100%;
  display: flex;
  // flex-direction: column;
  justify-content: space-between;
  flex-wrap: wrap;

  li {
    width: 48%;
    margin: 10px 0;

    p {
      margin-bottom: 5px;
    }
  }
}

// 盘点明细表格样式
.inventory-detail-table {
  margin-top: 20px;
  width: 100%;
  overflow-x: auto;
}

.detail-table {
  width: 100%;
  min-width: 1400px; // 设置最小宽度确保表格不被压缩
  border-collapse: collapse;
  border: 1px solid #e4e7ed;
  table-layout: fixed; // 固定表格布局

  th,
  td {
    padding: 8px 12px; // 调整内边距
    text-align: center; // 居中对齐
    border-bottom: 1px solid #e4e7ed;
    border-right: 1px solid #e4e7ed;
    vertical-align: middle; // 垂直居中
    word-wrap: break-word; // 自动换行
    overflow: hidden;
  }

  th {
    background-color: #f5f7fa;
    font-weight: 600;
    color: #606266;
    white-space: nowrap; // 表头不换行
  }

  // 设置各列宽度
  th:nth-child(1),
  td:nth-child(1) {
    width: 50px;
  }

  // #
  th:nth-child(2),
  td:nth-child(2) {
    width: 120px;
  }

  // 食材名称
  th:nth-child(3),
  td:nth-child(3) {
    width: 100px;
  }

  // 规格型号
  th:nth-child(4),
  td:nth-child(4) {
    width: 60px;
  }

  // 单位
  th:nth-child(5),
  td:nth-child(5) {
    width: 150px;
  }

  // 入库单价
  th:nth-child(6),
  td:nth-child(6) {
    width: 150px;
  }

  // 采购总数
  th:nth-child(7),
  td:nth-child(7) {
    width: 150px;
  }

  // 实到总数
  th:nth-child(8),
  td:nth-child(8) {
    width: 100px;
  }

  // 全部入库
  th:nth-child(9),
  td:nth-child(9) {
    width: 100px;
  }

  // 总价
  th:nth-child(10),
  td:nth-child(10) {
    width: 175px;
  }

  // 生产日期
  th:nth-child(11),
  td:nth-child(11) {
    width: 175px;
  }

  // 保质期
  th:nth-child(12),
  td:nth-child(12) {
    width: 140px;
  }

  // 仓库
  th:nth-child(13),
  td:nth-child(13) {
    width: 140px;
  }

  // 存储区域
  th:nth-child(14),
  td:nth-child(14) {
    width: 100px;
  }

  // 立即出库
  th:nth-child(15),
  td:nth-child(15) {
    width: 80px;
  }

  // 操作

  tr:last-child td {
    border-bottom: none;
  }

  td:last-child,
  th:last-child {
    border-right: none;
  }
}

// 调整表格中的输入框样式
.detail-table .el-input,
.detail-table .el-select,
.detail-table .el-input-number {
  width: 100%;
  max-width: 120px;
}

.detail-table .el-date-picker {
  width: 100%;
  max-width: 130px;
}

// 特定列的样式调整
.detail-table td:nth-child(2) {
  text-align: left;
}

// 食材名称左对齐
.detail-table td:nth-child(3) {
  text-align: left;
}

// 规格型号左对齐
.detail-table td:nth-child(9) {
  text-align: right;
}

// 总价右对齐

// 差异数量为负数时显示红色
.detail-table tbody td:nth-child(7) {
  color: #67c23a; // 默认绿色

  &.negative {
    color: #f56c6c; // 负数红色
  }
}

.search-select {
  width: 320px;
}

.form-list-lock {
  margin: 20px 0;
  width: 100%;
  display: flex;
  // flex-direction: column;
  justify-content: space-between;
  flex-wrap: wrap;

  li {
    width: 48%;
    margin: 10px 0;

    p {
      margin-bottom: 5px;
    }
  }
}

.drawer-content-zongjia {
  background-color: #f9f9f9;
  margin-bottom: 20px;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;

  p {
    padding: 0 10px;
    font-size: 16px;
  }
}

/* 上传图片相关样式 */
.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  margin: 20px auto;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 200px;
  height: 200px;
  display: block;
  object-fit: contain;
}

/* 打印专用样式 */
@media print {

  /* 隐藏不需要打印的元素 */
  .no-print {
    display: none !important;
  }

  /* 打印时的页面设置 */
  @page {
    margin: 20mm;
    size: A4;
  }

  /* 打印内容的样式 */
  #printMe {
    font-size: 12px;
    line-height: 1.5;
  }

  /* 打印时表格样式 */
  .el-table {
    width: 100% !important;
    border-collapse: collapse !important;
  }

  .el-table th,
  .el-table td {
    border: 1px solid #000 !important;
    padding: 8px !important;
  }

  /* 打印时表单样式 */
  .el-form-item {
    margin-bottom: 10px !important;
  }

  /* 打印标题样式 */
  .print-title {
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  /* 打印时间 */
  .print-time {
    text-align: right;
    margin-bottom: 15px;
    font-size: 12px;
  }
}
</style>